Easy
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
1 | 3 |
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 | 1 |
Return false.
虽然简单,但仍然不能小看的一道题。判断一棵树是否是平衡二叉树,平衡二叉树定义如下:
它是一棵空树或它的左右两个子树的高度差的绝对值不超过 1,并且左右两个子树都是一棵平衡二叉树。
递归+递归
最外面的递归用来判断一棵树和他的子树是不是平衡二叉树,最里面的递归用来计算左右子树的高度(采用回溯方法计算高度)
1 | class Solution: |